package com.fengyi.library.controller;

import com.fengyi.library.DTO.BookDTO;
import com.fengyi.library.model.Book;
import com.fengyi.library.model.Loan;
import com.fengyi.library.model.User;
import com.fengyi.library.service.BookService;
import com.fengyi.library.service.LoanService;
import com.fengyi.library.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;

@Controller
@RequestMapping("/loans")
public class LoanController {

    private final LoanService loanService;
    private final BookService bookService;
    private final UserService userService;

    @Autowired
    public LoanController(LoanService loanService, BookService bookService, UserService userService) {
        this.loanService = loanService;
        this.bookService = bookService;
        this.userService = userService;
    }

    @GetMapping("/my")
    public String myLoans(@RequestParam(defaultValue = "0") int page,
                         @RequestParam(defaultValue = "10") int size,
                         Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = userService.findByUsername(auth.getName());
        
        // 获取当前借阅
        List<Loan> currentLoans = loanService.findCurrentLoansByUser(user);
        model.addAttribute("currentLoans", currentLoans);
        model.addAttribute("currentLoansCount", currentLoans.size());
        
        // 获取历史借阅
        List<Loan> historyLoans = loanService.findReturnedLoansByUser(user);
        model.addAttribute("historyLoans", historyLoans);
        model.addAttribute("returnedLoansCount", historyLoans.size());
        
        // 获取逾期借阅
        List<Loan> overdueLoans = loanService.findOverdueLoansByUser(user);
        model.addAttribute("overdueLoans", overdueLoans);
        model.addAttribute("overdueLoansCount", overdueLoans.size());
        
        // 分页信息
        model.addAttribute("historyCurrentPage", page);
        model.addAttribute("historyTotalPages", (int) Math.ceil(historyLoans.size() / (double) size));
        model.addAttribute("historyTotalItems", historyLoans.size());
        
        return "loans/my-loans";
    }

    @PostMapping("/borrow/{bookId}")
    public String borrowBook(@PathVariable Integer bookId,
                        @RequestParam(defaultValue = "30") int days,
                        RedirectAttributes redirectAttributes) {
        try {
            // 获取当前登录用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.findByUsername(auth.getName());
            if (user == null) {
                throw new RuntimeException("用户未登录或不存在");
            }
            
            // 获取图书信息
            BookDTO bookDTO = bookService.findById(bookId);
            if (bookDTO == null) {
                throw new RuntimeException("图书不存在");
            }
            
            // 将BookDTO转换为Book实体
            Book book = new Book();
            book.setId(bookDTO.getId());
            book.setTitle(bookDTO.getTitle());
            book.setAuthor(bookDTO.getAuthor());
            book.setPublisher(bookDTO.getPublisher());
            book.setPublicationYear(bookDTO.getPublicationYear());
            book.setIsbn(bookDTO.getIsbn());
            book.setCategory(bookDTO.getCategory());
            book.setDescription(bookDTO.getDescription());
            book.setQuantity(bookDTO.getQuantity());
            book.setAvailableQuantity(bookDTO.getAvailableQuantity());
            book.setCreatedAt(bookDTO.getCreatedAt());
            book.setUpdatedAt(bookDTO.getUpdatedAt());
            
            // 检查是否已借阅此书
            if (loanService.hasUserBorrowedBook(user, book)) {
                redirectAttributes.addFlashAttribute("error", "您已借阅此书，不能重复借阅");
                return "redirect:/books/view/" + bookId;
            }
            
            // 执行借书操作
            loanService.borrowBook(user, book, days);
            redirectAttributes.addFlashAttribute("success", "借阅成功，请在" + days + "天内归还");
            
            // 成功借阅后重定向到"我的借阅"页面
            return "redirect:/loans/my";
            
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("借书失败: " + e.getMessage());
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "借阅失败: " + e.getMessage());
            return "redirect:/books/view/" + bookId;
        }
    }

    @PostMapping("/return/{loanId}")
    public String returnBookByPathVariable(@PathVariable Integer loanId, RedirectAttributes redirectAttributes) {
        try {
            loanService.returnBook(loanId);
            redirectAttributes.addFlashAttribute("success", "图书归还成功");
            return "redirect:/loans/my";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "归还失败: " + e.getMessage());
            return "redirect:/loans/my";
        }
    }
    
    @PostMapping("/return")
    public String returnBook(@RequestParam Integer loanId, RedirectAttributes redirectAttributes) {
        try {
            loanService.returnBook(loanId);
            redirectAttributes.addFlashAttribute("success", "图书归还成功");
            return "redirect:/loans/my";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "归还失败: " + e.getMessage());
            return "redirect:/loans/my";
        }
    }
    
    @PostMapping("/admin/return")
    public String adminReturnBook(@RequestParam Integer loanId, 
                                RedirectAttributes redirectAttributes,
                                HttpServletRequest request,
                                HttpServletResponse response) {
        try {
            loanService.returnBook(loanId);
            
            // 检查是否是AJAX请求
            if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                response.setStatus(HttpServletResponse.SC_OK);
                return null; // 对于AJAX请求，不需要返回视图
            }
            
            redirectAttributes.addFlashAttribute("success", "图书归还成功");
            return "redirect:/loans/admin/all-loans";
        } catch (Exception e) {
            if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }
            
            redirectAttributes.addFlashAttribute("error", "归还失败: " + e.getMessage());
            return "redirect:/loans/admin/all-loans";
        }
    }

    @GetMapping("/admin/all-loans")
    public String allLoans(@RequestParam(defaultValue = "0") int page,
                      @RequestParam(defaultValue = "20") int size,
                      @RequestParam(required = false) String keyword,
                      Model model) {
        // 使用findAllLoans方法会自动检查并更新逾期状态
        Page<Loan> loanPage;
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 如果有关键词，执行搜索
            loanPage = loanService.searchLoans(
                    keyword, PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "borrowDate"))
            );
            model.addAttribute("keyword", keyword);
        } else {
            // 否则获取所有借阅
            loanPage = loanService.findAllLoans(
                    PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "borrowDate"))
            );
        }
        
        model.addAttribute("loans", loanPage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", loanPage.getTotalPages());
        model.addAttribute("totalItems", loanPage.getTotalElements());
        
        return "admin/loans";
    }
    

    @GetMapping("/admin/overdue")
    @PreAuthorize("hasRole('ADMIN')")
    public String overdueLoans(@RequestParam(defaultValue = "0") int page,
                               @RequestParam(defaultValue = "10") int size,
                               Model model) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "dueDate"));
        // Assuming loanService has a method like findAllOverdueLoans(Pageable pageable)
        Page<Loan> overdueLoanPage = loanService.findAllOverdueLoans(pageable); 

        model.addAttribute("loans", overdueLoanPage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", overdueLoanPage.getTotalPages());
        model.addAttribute("totalItems", overdueLoanPage.getTotalElements());
        model.addAttribute("pageTitle", "逾期借阅"); // "Overdue Loans" in Chinese
        model.addAttribute("listType", "overdue"); // For template differentiation

        return "admin/overdue-loans"; // Path to the Thymeleaf template
    }

    // 删除了手动更新借阅状态和查看逾期借阅的相关方法
}
